package com.erp.app.report.genericInquiry;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;

import sun.misc.BASE64Encoder;

import com.erp.app.common.attachment.beans.AttachmentVo;
import com.erp.app.common.attachment.pk.AttachmentPk;
import com.erp.app.common.select.beans.SelectDelegate;
import com.erp.app.report.genericInquiry.inquiryCriteria.beans.vo.InquiryCriteriaVO;
import com.erp.app.report.genericInquiry.inquiryDisplay.beans.vo.InquiryDisplayVO;
import com.erp.app.report.genericInquiry.inquiryMaster.beans.GenericInquiryImageVo;
import com.erp.app.report.genericInquiry.inquiryMaster.beans.GenericInquiryMasterVO;
import com.erp.app.report.genericInquiry.inquiryMaster.beans.GenericInquiryMultipartVo;
import com.erp.app.report.genericInquiry.inquiryOutput.beans.vo.InquiryOutputVO;
import com.erp.app.report.genericInquiry.inquirySp.beans.vo.InquirySpVO;
import com.erp.framework.types.CustomBigInteger;
import com.erp.framework.util.CommonUtil;
import com.lowagie.text.Image;

public class GenericInquiryTxtGenerator extends GenericFileGenerator {

	private static final String ACTION_CREATE_TXT = "createTxt";
	private static final String ACTION_CREATE_HTML_TXT = "createHtmlTxt";
	private static final String FIELD_TYPE_MULTIPART = "MULTIPART_";
	private static final String FIELD_TYPE_MULTIPART_INIT = "MULTIPART_INIT";
	private static final String FIELD_TYPE_MULTIPART_NEXT_PART = "MULTIPART_NEXT_PART";
	private static final String FIELD_TYPE_MULTIPART_HTML_FILE = "MULTIPART_HTML_FILE";
	private static final String FIELD_TYPE_MULTIPART_IMAGE_FILE = "MULTIPART_IMAGE_FILE";
	private static final String FIELD_TYPE_MULTIPART_IMAGE_ROW_HEIGHT = "MULTIPART_IMAGE_ROW_HEIGHT";
	
    public GenericInquiryTxtGenerator(GenericInquirySearchForm form) {
		super(form);
	}

	protected void preprocess(
			HttpServletRequest request, 
			HttpServletResponse response,
            ActionServlet servlet, 
            ActionErrors errors) {
		
		String filename = "";
		if(ACTION_CREATE_TXT.equals(form.getPageEventSrc())){
			filename = CommonUtil.toValidFileName(form.getFilename()) + ".txt\"";
		} else if(ACTION_CREATE_HTML_TXT.equals(form.getPageEventSrc())){
			filename = CommonUtil.toValidFileName(form.getFilename()) + ".xls\"";
		}
        response.setHeader("Content-disposition", "attachment; filename=\""  + filename);
    }

    protected ByteArrayOutputStream genContent(
            ActionMapping mapipng, 
            HttpServletRequest request, 
            HttpServletResponse response,
            ActionServlet servlet, 
            ActionErrors errors) throws Exception {
        
        HttpSession session = request.getSession(false);
        StringBuffer rslt = new StringBuffer();
        
        GenericInquiryMasterVO vo = form.getGenericInquiryMasterVO();
        Collection spList = vo.getLocalChilds(InquirySpVO.class);
        Collection displayList = vo.getLocalChilds(InquiryDisplayVO.class);
        Collection critList = vo.getLocalChilds(InquiryCriteriaVO.class);
        Collection rsltList = form.getReportResultList();
        InquiryDisplayVO displayVO = null;
        InquiryOutputVO rsltVO = null;
        InquirySpVO spVO = (InquirySpVO)spList.iterator().next();
        InquiryCriteriaVO critVO = null;
        GenericInquiryMultipartVo multipartVo = null;
        ArrayList imageList = new ArrayList();
        
//      Header & Content
        for (Iterator rsltIt = rsltList.iterator(); rsltIt.hasNext();) {
            rsltVO = (InquiryOutputVO)rsltIt.next();
            int counter = 0;
            String field02 = CommonUtil.nullToString(rsltVO.getField(1));
            if(ACTION_CREATE_HTML_TXT.equals(form.getPageEventSrc())
            	&& !CommonUtil.isEmpty(field02)
            	&& field02.startsWith(FIELD_TYPE_MULTIPART)
            ){
            	if(FIELD_TYPE_MULTIPART_INIT.equals(field02)){
                    String field01 = CommonUtil.nullToString(rsltVO.getField(0));
                    String field03 = CommonUtil.nullToString(rsltVO.getField(2));
                    multipartVo = new GenericInquiryMultipartVo();
                    multipartVo.setBoundary(field01);
                    multipartVo.setImageTdClass(field03);
                    rslt.append("Content-Type: multipart/related; boundary=\""+field01+"\"");
            	}else if(FIELD_TYPE_MULTIPART_NEXT_PART.equals(field02)){
            		if(multipartVo!=null){
            			rslt.append("--"+multipartVo.getBoundary());
            		}
            	}else if(FIELD_TYPE_MULTIPART_HTML_FILE.equals(field02)){
            		if(multipartVo!=null){
            			rslt.append("Content-Location: file:///C:/"+String.valueOf(multipartVo.getHtmlFileCount())+".htm");
            			multipartVo.setHtmlFileCount(multipartVo.getHtmlFileCount()+1);
            		}
            	}else if(FIELD_TYPE_MULTIPART_IMAGE_FILE.equals(field02)){
            		if(multipartVo!=null){
            			int imageFileCount = multipartVo.getImageFileCount();
            			String tdClass = CommonUtil.nullToString(multipartVo.getImageTdClass());
            			String attachLineNo =  CommonUtil.nullToString(rsltVO.getField(0));
            			String rowspan =  CommonUtil.nullToString(rsltVO.getField(2));
            			float  specificWidth = 0;
            			float  specificHeight = 0;
            			if(CommonUtil.isValidNumber(rsltVO.getField(4))){
            				specificWidth = Float.valueOf(rsltVO.getField(4)).floatValue();
            			}
                        if(CommonUtil.isValidNumber(rsltVO.getField(5))){
                        	specificHeight = Float.valueOf(rsltVO.getField(5)).floatValue();
            			}
            			SelectDelegate sdg = new SelectDelegate();
            			AttachmentVo attachmentVo = null;
            			try{
            				if(!CommonUtil.isEmpty(attachLineNo)){
                    			attachmentVo = (AttachmentVo) sdg.findByPrimaryKey(new AttachmentVo(), new AttachmentPk(rsltVO.getCompanyCode(), CustomBigInteger.customize(attachLineNo)));
            				}
            			}catch(Exception e){
            				System.out.println("can't find attachment -- "+attachLineNo);
            			}
            			if(attachmentVo!=null){
            				String contentType = CommonUtil.nullToString(attachmentVo.getAttachmentContentType());
            				if(contentType.startsWith("image")){
            					String fileName = multipartVo.getImageFileCount() + "/" + CommonUtil.nullToString(attachmentVo.getAttachmentFileName());
	                            Image itemImage = Image.getInstance(attachmentVo.getAttachment());
	                            float maxRectangle = 350.0f;
	                            if(!CommonUtil.isEmpty(spVO.getMaxImageSize()) && spVO.getMaxImageSize().compareTo(new BigDecimal(350))<0){
		                            maxRectangle = spVO.getMaxImageSize().floatValue();
	                            }
	                            float originHeight = itemImage.plainHeight();
	                            float originWidth = itemImage.plainWidth();
	                            int imageWidth=0;
	                            int imageHeight=0;
	                            if (specificWidth<1||specificHeight<1) {
	                            	//set default value
									if (originWidth > maxRectangle
											&& originWidth >= originHeight) {
										imageWidth = (int) (maxRectangle);
										imageHeight = (int) (originHeight
												* maxRectangle / originWidth);
									} else if (originHeight > maxRectangle
											&& originHeight >= originWidth) {
										imageHeight = (int) maxRectangle;
										imageWidth = (int) (originWidth
												* maxRectangle / originHeight);
									} else {
										imageWidth = (int) originWidth;
										imageHeight = (int) originHeight;
									}
									imageHeight = (int) (imageHeight * 72 / 96);
									imageWidth = (int) (imageWidth * 72 / 96);
								}else{
									//set specific value, measurement:pt
									imageHeight = (int) specificHeight;
									imageWidth = (int)  specificWidth;
								}
								rslt.append("<td class="+tdClass);
                        		if(!CommonUtil.isEmpty(rowspan) && !("0".equals(rowspan)) && !("1".equals(rowspan))){
                            		rslt.append(" rowspan=3D"+rowspan);
                        		}
                        		rslt.append(" style=3D'height:"+String.valueOf(imageHeight+20)+"pt;width:"+String.valueOf(imageWidth+20)+"pt'><!--[if gte vml 1]>");
                                rslt.append("\r\n");
                                rslt.append("<v:shape style=3D'position:absolute;margin-left:10pt;margin-top:10pt;margin-right:10pt;margin-bottom:10pt;width:"+String.valueOf(imageWidth)+"pt;height:"+String.valueOf(imageHeight)+"pt;'>");
                                rslt.append("\r\n");
                                rslt.append("<v:imagedata src=3D\""+fileName+"\"/>");
                    			multipartVo.setImageFileCount(imageFileCount+1);
                                rslt.append("\r\n");
                                rslt.append("</v:shape><![endif]-->");
                                rslt.append("\r\n");
                                rslt.append("</td>");
                                
                                BASE64Encoder encode=new BASE64Encoder();
                                String base64Str = encode.encode(attachmentVo.getAttachment());

            					GenericInquiryImageVo imageVo = new GenericInquiryImageVo();
            					imageVo.setFileName(fileName);
            					imageVo.setContentType(contentType);
            					imageVo.setFileBase64Str(base64Str);
            					imageList.add(imageVo);
            				}
            			}else{
                    		rslt.append("<td class="+tdClass);
                    		if(!CommonUtil.isEmpty(rowspan) && !("0".equals(rowspan)) && !("1".equals(rowspan))){
                        		rslt.append(" rowspan=3D"+rowspan);
                    		}
                    		rslt.append("></td>");
            			}
            		}
            	}else if(FIELD_TYPE_MULTIPART_IMAGE_ROW_HEIGHT.equals(field02)){
            		if(multipartVo!=null){
            			int imageFileCount = multipartVo.getImageFileCount();
            			String tdClass = CommonUtil.nullToString(multipartVo.getImageTdClass());
            			String attachLineNo =  CommonUtil.nullToString(rsltVO.getField(0));
            			String rowspan =  CommonUtil.nullToString(rsltVO.getField(2));
            			String value =  CommonUtil.nullToString(rsltVO.getField(3));
            			SelectDelegate sdg = new SelectDelegate();
            			AttachmentVo attachmentVo = null;
            			try{
            				if(!CommonUtil.isEmpty(attachLineNo)){
                    			attachmentVo = (AttachmentVo) sdg.findByPrimaryKey(new AttachmentVo(), new AttachmentPk(rsltVO.getCompanyCode(), CustomBigInteger.customize(attachLineNo)));
            				}
            			}catch(Exception e){
            				System.out.println("can't find attachment -- "+attachLineNo);
            			}
            			if(attachmentVo!=null){
            				String contentType = CommonUtil.nullToString(attachmentVo.getAttachmentContentType());
            				if(contentType.startsWith("image")){
            					String fileName = multipartVo.getImageFileCount() + "/" + CommonUtil.nullToString(attachmentVo.getAttachmentFileName());
	                            Image itemImage = Image.getInstance(attachmentVo.getAttachment());
	                            float maxRectangle = 350.0f;
	                            if(!CommonUtil.isEmpty(spVO.getMaxImageSize())){
		                            maxRectangle = spVO.getMaxImageSize().floatValue();
	                            }
	                            float originHeight = itemImage.plainHeight();
	                            float originWidth = itemImage.plainWidth();
	                            int rowHeight;
	                            if(originWidth > maxRectangle && originWidth >= originHeight) {
	                            	rowHeight =  (int)(originHeight*maxRectangle/originWidth);
	                            } else if(originHeight > maxRectangle && originHeight >= originWidth) {
	                            	rowHeight = (int)maxRectangle;
	                            } else {
	                            	rowHeight = (int)originHeight;
	                            }
	                            rowHeight = (int)(rowHeight*72/96);
	                            rowHeight += 20;
                        		if(!CommonUtil.isEmpty(rowspan) && !("0".equals(rowspan)) && !("1".equals(rowspan)) && CommonUtil.isValidInteger(rowspan)){
                        			rowHeight = rowHeight/Integer.parseInt(rowspan);
                        		}
                        		rslt.append("<td class="+tdClass+" style=3D'height:"+String.valueOf(rowHeight)+"pt;'>"+value+"</td>");
            				}
            			}else{
                    		rslt.append("<td class="+tdClass+">"+value+"</td>");
            			}
            		}
            	}
            }else{
                for (Iterator displayIt = displayList.iterator(); displayIt.hasNext();) {
                    displayVO = (InquiryDisplayVO)displayIt.next();
                    rslt.append(CommonUtil.nullToString(rsltVO.getField(counter)));
                    counter++;
                }
            }
            rslt.append("\r\n");
        }
        
        if(multipartVo!=null){
        	if(imageList!=null && imageList.size()>0){
        		for(int i=0; i<imageList.size(); i++){
            		GenericInquiryImageVo imageVo = (GenericInquiryImageVo) imageList.get(i);
                	rslt.append("\r\n");
        			rslt.append("--"+multipartVo.getBoundary());
                	rslt.append("\r\n");
                	rslt.append("Content-Location: file:///C:/"+imageVo.getFileName());
                	rslt.append("\r\n");
                	rslt.append("Content-Transfer-Encoding: base64");
                   	rslt.append("\r\n");
                   	rslt.append("Content-Type: "+imageVo.getContentType());
                   	rslt.append("\r\n");
                   	rslt.append("\r\n");
                   	rslt.append(imageVo.getFileBase64Str());
                   	rslt.append("\r\n");
        		}
        	}

        	rslt.append("\r\n");
			rslt.append("--"+multipartVo.getBoundary());
        	rslt.append("\r\n");
        	rslt.append("Content-Location: file:///C:/filelist.xml");
           	rslt.append("\r\n");
        	rslt.append("Content-Transfer-Encoding: quoted-printable");
        	rslt.append("\r\n");
        	rslt.append("Content-Type: text/xml; charset=\"utf-8\"");
           	rslt.append("\r\n");
        	rslt.append("\r\n");
        	rslt.append("<xml xmlns:o=3D\"urn:schemas-microsoft-com:office:office\">");
        	rslt.append("\r\n");
        	for(int i=1; i<=(multipartVo.getHtmlFileCount()-1); i++){
        		if(i==1){
                	rslt.append("<o:MainFile HRef=3D\"1.htm\"/>");
        		}else{
                	rslt.append("<o:File HRef=3D\""+String.valueOf(i)+".htm\"/>");
        		}
             	rslt.append("\r\n");
        	}
        	if(imageList!=null && imageList.size()>0){
        		for(int i=0; i<imageList.size(); i++){
            		GenericInquiryImageVo imageVo = (GenericInquiryImageVo) imageList.get(i);
                	rslt.append("<o:File HRef=3D\""+imageVo.getFileName()+"\"/>");
                 	rslt.append("\r\n");
        		}
        	}
         	rslt.append("<o:File HRef=3D\"filelist.xml\"/>");
         	rslt.append("\r\n");
         	rslt.append("</xml>");
        	rslt.append("\r\n");
			rslt.append("--"+multipartVo.getBoundary()+"--");
        	rslt.append("\r\n");
        }
        
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(rslt.toString().getBytes());
        
        return baos;
	}
}
